<template>
  <div>
    <el-dialog
      v-model="currentOpen"
      :close-on-click-modal="false"
      :title="title"
      :before-close="handleClose"
      width="800px"
    >
      <el-form
        ref="editForm"
        inline
        :rules="rules"
        :model="form"
        label-width="180px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="服务商简称" prop="serviceSimpleName" :label-position="labelPosition">
              <el-input v-model="form.serviceSimpleName" placeholder="请输入服务商简称" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务商全称" prop="serviceWholeName" :label-position="labelPosition">
              <el-input v-model="form.serviceWholeName" placeholder="请输入服务商全称" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="status" :label-position="labelPosition">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dicts[DictDirection.通用状态]"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                  :value="dict.dictLabel"
                >
                  {{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结算模式" prop="settlementMode" :label-position="labelPosition">
              <el-select v-model="form.settlementMode" style="width: 100%;" clearable>
                <el-option
                  v-for="dict in dicts[DictDirection.客户结算模式]"
                  :key="dict.dictLabel"
                  placeholder="请选择结算模式"
                  :label="dict.dictLabel"
                  :value="dict.dictLabel"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="类型" prop="type" :label-position="labelPosition">
              <el-select v-model="form.type" style="width: 100%;" clearable>
                <el-option
                  v-for="dict in dicts[DictDirection.服务商类型]"
                  :key="dict.dictValue"
                  placeholder="请选择服务商类型"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属机构" prop="affiliation" :label-position="labelPosition">
              <el-select v-model="form.affiliation" style="width: 100%;">
                <el-option
                  v-for="dict in dicts[DictDirection.收货站点]"
                  :key="dict.deptId"
                  placeholder="请选择所属机构"
                  :label="dict.deptName"
                  :value="dict.deptId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="付款账号" prop="paymentAccount" :label-position="labelPosition">
              <el-input v-model="form.paymentAccount" placeholder="请输入付款账号" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开户行" prop="bank" :label-position="labelPosition">
              <el-input v-model="form.bank" placeholder="请输入开户行" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="纳税人识别号" prop="identificationNumber" :label-position="labelPosition">
              <el-input v-model="form.identificationNumber" placeholder="请输入纳税人识别号" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模板" prop="template" :label-position="labelPosition">
              <el-input v-model="form.template" placeholder="请输入模板" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="汇率" prop="exchangeRate" :label-position="labelPosition">
              <el-input
                v-model="form.exchangeRate"
                placeholder="请输入汇率"
                :controls="false"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务商联系人" prop="providerContact" :label-position="labelPosition">
              <el-input v-model="form.providerContact" placeholder="请输入服务商联系人" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="服务商联系电话" prop="providerPhone" :label-position="labelPosition">
              <el-input v-model.trim="form.providerPhone" placeholder="请输入服务商联系电话" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="财务姓名" prop="providerFinancial" :label-position="labelPosition">
              <el-input v-model="form.providerFinancial" placeholder="请输入财务姓名" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="财务联系电话" prop="providerFinancialPhone" :label-position="labelPosition">
              <el-input v-model="form.providerFinancialPhone" placeholder="请输入财务联系电话" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用日期" prop="openingDate" :label-position="labelPosition">
              <el-date-picker
                v-model="form.openingDate"
                type="datetime"
                placeholder="选择日期时间"
                style="width: 100%;"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="作废日期" prop="obsoleteDate" :label-position="labelPosition">
              <el-date-picker
                v-model="form.obsoleteDate"
                type="datetime"
                placeholder="选择日期时间"
                style="width: 100%;"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址" prop="address" :label-position="labelPosition">
              <el-input v-model="form.address" placeholder="请输入地址" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业执照" prop="businessLicense" :label-position="labelPosition">
              <el-upload
                ref="upload"
                multiple
                accept="image/png,image/gif,image/jpg,image/jpeg"
                :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport"
                :disabled="upload.isUploading"
                :auto-upload="false"
                list-type="picture"
                :on-progress="handleFileUploadProgress"
                :on-remove="handleRemoveFile"
                :before-upload="beforeAvatarUpload" 
                :on-change="handleFileChange"
                :http-request="uploadFile"
                :file-list="showBusinessLicenseFileList"
              >
                <el-button type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同" prop="contract" :label-position="labelPosition">
              <el-upload
                ref="upload2"
                action="#"
                :disabled="upload.isUploading"
                multiple
                :on-change="handleFileChange2"
                :on-remove="handleRemoveFile2"
                :file-list="showContractFileList"
                :auto-upload="false"
                :http-request="uploadFile2"
              >
                <el-button type="primary" :disabled="upload.isUploading">点击上传</el-button>
              </el-upload>
            </el-form-item> 
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div>
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template> 

<script lang="ts" setup>
import { computed, ref, defineAsyncComponent, getCurrentInstance, defineEmits, reactive, defineExpose } from 'vue'
import { Plus, Edit, Delete, Search, Upload, Bottom, Key, UploadFilled } from '@element-plus/icons-vue'
import { ElButton, ElMessageBox, ElMessage, ElSwitch } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'
import useDicts, { DictDirection } from '@/store/modules/dicts'
import { add, edit, getListInfo } from '@/api/BusinessConfig/serviceProvider'
import { getToken, getTokenType } from '@/utils/auth'
import { compressImg } from '@/utils/index'
// 图片的数组

let
  // eslint-disable-next-line prefer-const
  formData = ref(null)
const props = defineProps({
  open: {
    type: Boolean,
  },
  title: {
    type: String,
    default: '',
  },
})

const emit = defineEmits(['update:open', 'update:title', 'changeList'])
const labelPosition = ref('right')
const dicts = useDicts()
dicts.setDicts(DictDirection.服务商类型)
dicts.setDicts(DictDirection.通用状态)
dicts.setDicts(DictDirection.客户结算模式)
dicts.setDicts(DictDirection.收货站点)
const tokenType = getTokenType()
const 
  upload = reactive({
    isUploading: false,
    updateSupport: 0,
    headers: { Authorization: `${ tokenType }${ getToken() }` },
    url: `${ import.meta.env.VITE_BASE_API }/system/user/importData`,
  })
let 
  fileListBusinessLicense = [],
  fileListContract = [],
  showBusinessLicenseFileList = ref<UploadUserFile[]>([]),
  showContractFileList = ref<UploadUserFile[]>([])
const editForm = ref(null),
  {
    proxy,
  }:{
    proxy:any
  } = getCurrentInstance()
const handleFileUploadProgress = () => {
  upload.isUploading = true
}

const currentOpen = computed({
  get() {
    return props.open
  },
  set(val) {
    emit('update:open', val)
  },
})
const beforeAvatarUpload = (file) => {
  upload.isUploading = false
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return isLt2M
  }
}
async function uploadFile(file) {
  formData.value.append('businessLicense', file.file)
}
async function uploadFile2(file) {
  formData.value.append('contract', file.file)
}
const form = ref({
  status: 1,
  serviceSimpleName: undefined,
  serviceWholeName: undefined,
  settlementMode: undefined,
  type: undefined,
  affiliation: undefined,
  paymentAccount: undefined,
  bank: undefined,
  identificationNumber: undefined,
  template: undefined,
  providerContact: undefined,
  providerPhone: undefined,
  providerFinancial: undefined,
  providerFinancialPhone: undefined,
  openingDate: undefined,
  obsoleteDate: undefined,
  address: undefined,
  exchangeRate: undefined,
  businessLicense: undefined,
  businessLicenseFiles: [],
  contract: undefined,
  contractFiles: [],
  id: undefined,
})
const rules = {
  providerFinancialPhone: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur',
    },
  ],
  providerPhone: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur',
    },
  ],
  providerServiceCode: [{ required: true, message: '请输入服务商代码', trigger: 'blur' }],
  serviceSimpleName: [{ required: true, message: '请输入服务商简称', trigger: 'blur' }],
  serviceWholeName: [{ required: true, message: '请输入服务商全称', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: ['blur', 'change'] }],
  settlementMode: [
    {
      required: true,
      message: '请选择结算模式',
      trigger: ['blur', 'change'],
    },
  ],
  type: [{ required: true, message: '请选择类型', trigger: ['blur', 'change'] }],
  openingDate: [{
    required: true,
    message: '启用日期必须选择',
    trigger: ['change', 'blur'],
  }],
  obsoleteDate: [{
    required: true,
    message: '作废日期必须选择',
    trigger: ['change', 'blur'],
  }],
}

// 重置表单
const reset = () => {
  form.value = {
    status: 1,
    serviceSimpleName: undefined,
    serviceWholeName: undefined,
    settlementMode: undefined,
    type: undefined,
    affiliation: undefined,
    paymentAccount: undefined,
    bank: undefined,
    identificationNumber: undefined,
    template: undefined,
    providerContact: undefined,
    providerPhone: undefined,
    providerFinancial: undefined,
    providerFinancialPhone: undefined,
    openingDate: undefined,
    obsoleteDate: undefined,
    address: undefined,
    exchangeRate: undefined,
    businessLicense: undefined,
    businessLicenseFiles: [],
    contract: undefined,
    contractFiles: [],
    id: undefined,
  }
  proxy.$resetForm(editForm.value)
}
// 文件状态改变,添加文件，上传成功，上传失败都会调用
const handleFileChange = (file, fileList1) => {
  fileListBusinessLicense = fileList1
  form.value.businessLicense = fileList1.raw
}
const handleFileChange2 = (file, fileList) => {
  fileListContract = fileList
  form.value.contract = fileList.raw
}
const handleRemoveFile = (file, uploadFiles) => {
  showBusinessLicenseFileList.value = uploadFiles
  form.value.businessLicense = uploadFiles.map(el => el.url)
}
const handleRemoveFile2 = (file, uploadFiles) => {
  showContractFileList.value = uploadFiles
  form.value.contract = uploadFiles.map(el => el.url)
}
// 提交
const submitForm = () => {
  // 改参数
  proxy.$validateForm(editForm.value, async () => {
    // 图片压缩 promise类型
    let zipImg = async function ({ data, key }) {
        // eslint-disable-next-line
              return new Promise<void>(async (resolve, reject) => {
          try {
            const list = data.getAll(key)
            let nList = []
            for (const item of list) {
              const i = await compressImg({ file: item })
              nList.push(i)
            }
            data.delete(key)
            for (const item of nList) {
              data.append(key, item)
            }
            resolve()
          } catch (error) {
            console.log(error)
            reject(error)
          }
        })
      },
      res,
      msg
    formData.value = new FormData()
    upload.isUploading = true
    fileListBusinessLicense.forEach(el => {
      if (el.status === 'ready') {
        formData.value.append('businessLicenses', el.raw)
      }
    })
    fileListContract.forEach(el => {
      if (el.status === 'ready') {
        formData.value.append('contracts', el.raw)
      }
    })
    // 挂载form数据
    formData.value.append('serviceProvider', JSON.stringify(form.value))
    // 挂载文件上传
    proxy.$refs.upload.submit()
    // 图片压缩
    await zipImg({ data: formData.value, key: 'businessLicenses' })
    await zipImg({ data: formData.value, key: 'contracts' })
    // 发送请求
    if (form.value.id != undefined) {
      res = await edit(formData.value)
      msg = '修改成功'
    } else {
      res = await add(formData.value)
      msg = '新增成功'
      emit('changeList')
    }
    upload.isUploading = false
    if (res.code == 200) {
      ElMessage.success(msg)
      // 上传成功清除文件
      proxy.$refs.upload.clearFiles()
      emit('update:open', false)
      reset()
      // 刷新列表
      emit('changeList')
    }
  })
}
const cancel = () => {
  reset()
  emit('update:open', false)
}
const handleClose = () => {
  reset()
  emit('update:open', false)
}
const getDetail = (id) => {
  showBusinessLicenseFileList.value = []
  showContractFileList.value = []
  getListInfo(id).then((res) => {
    if (res.code === 200) {
      form.value = res.data
      if (form.value.businessLicenseFiles && form.value.businessLicenseFiles.length) {
        form.value.businessLicenseFiles = form.value.businessLicenseFiles.map(el => {
          console.log(el, '888')
          const result = { url: undefined, name: undefined }
          result.url = el
          const arr = el.split('/')
          result.name = arr[arr.length - 1]
          showBusinessLicenseFileList.value.push(result)
          form.value.businessLicenseFiles.push(el)
          return el      
        })
      } else if (form.value.contractFiles && form.value.contractFiles.length) {
        form.value.contractFiles = form.value.contractFiles.map(el => {
          const result = { url: undefined, name: undefined }
          result.url = el
          const arr = el.split('/')
          result.name = arr[arr.length - 1]
          showContractFileList.value.push(result)
          form.value.businessLicenseFiles.push(el)
          return el
        })
      }
    } 
  })
}

defineExpose({
  getDetail,
})
</script>